package com.yl.zqy.utils;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.yl.zqy.common.CustomException;
import com.yl.zqy.enums.ResultCode;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;


@Slf4j
public final class ExcelUtil {
    private ExcelUtil() {
    }

    public static ExcelWriter getExcelWriter(String fileName, HttpServletResponse response) {
        try {
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String name = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replace("+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + name + ".xlsx");
            OutputStream out = response.getOutputStream();
            return EasyExcelFactory.write(out).build();
        } catch (Exception e) {
            throw new CustomException(ResultCode.FILE_DOWNLOAD_ERROR);
        }
    }

    public static void onException(Exception exception, List<String> errorMessages) {
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            String message = String.format("第%s行，第%s列解析异常，数据为:%s 解析下一行", excelDataConvertException.getRowIndex(),
                    excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData().getStringValue());
            log.error(message, excelDataConvertException);
            errorMessages.add(message);
        } else {
            errorMessages.add(exception.getMessage());
            log.error("解析失败，但是继续解析下一行", exception);
        }
    }
}
